import Food from './food'
import ScorePanel from './scorePanel'
import Snake from './snake'
class GameControl {
    //定义三个属性
    //蛇
    snake: Snake;
    //食物
    food: Food;
    //计分器
    scorePanel: ScorePanel;

    //游戏容器id名字
    parentNodeIdName: string
    //存储按键的key
    direction: string = 'ArrowRight'

    //记录游戏是否结束
    islive: boolean = true
    constructor(parentNodeIdName: string = "stage") {
        this.parentNodeIdName = parentNodeIdName
        this.snake = new Snake(parentNodeIdName)
        this.food = new Food(parentNodeIdName)
        this.scorePanel = new ScorePanel(10, 5)
        this.init()
    }

    //游戏初始化方法
    init() {
        //bind是创建一个新函数 并绑定当前对象的this 
        //因为this.keydownHandler绑定的是document
        //所以 keydownHandler函数里this指向是document
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        //调用run方法 使蛇移动
        this.run()
    }
    keydownHandler(event: KeyboardEvent) {
        //检查用户按下的键是否是上下左右四个键
        this.direction = event.key
    }

    //蛇运动的方法
    run() {
        let Y = this.snake.y
        let X = this.snake.x
        //计算想x,y的值
        switch (this.direction) {
            case 'ArrowUp':
            case 'Up':
                //按上键让蛇往上走 就是top值越小
                Y -= 10
                break
            case 'ArrowDown':
            case 'Down':
                Y += 10
                break
            case 'ArrowLeft':
            case 'Left':
                X -= 10
                break
            case 'ArrowRight':
            case 'Right':
                X += 10
                break
        }
        //检查蛇是否吃到食物了
        this.checkEat(X, Y)

        //设置X，Y的值
        try {
            this.snake.setX(X)
            this.snake.setY(Y)
        } catch (e) {
            alert((e as Error).message + 'Game Over')
            this.islive = false
        }
        //开启定时调用
        let time = 300 - (this.scorePanel.level - 1) * 30
        this.islive && setTimeout(this.run.bind(this), time);
    }

    //检查蛇是否吃到食物了
    checkEat(X: number, Y: number) {
        if (X === this.food.x && Y === this.food.y) {
            this.food.change() //改变食物位置
            this.scorePanel.addScore() //计分器增加一分
            this.snake.addBody() //蛇长大
        }
    }

}

export default GameControl